package io.github.yotta.export.core.provider;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author yotta
 * @date 2023/10/25 14:52
 */
public class LocalFileProvider implements FileProvider {


    private final String baseDir;

    public LocalFileProvider(String baseDir) {
        this.baseDir = baseDir.replaceFirst("^~", System.getProperty("user.home"));
    }

    @Override
    public String generateFilePath(String fileName, String ext) {
        return Paths.get(
                baseDir,                // 父目录
                fileName,
                LocalDateTime.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT)),  // 时间归组
                fileName + ext
        ).toString();
    }


    @Override
    public void saveFile(String filePath, File file) throws IOException {
        FileUtils.copyFile(file, new File(filePath));
    }

    public InputStream openFile(String filePath) throws IOException {
        return Files.newInputStream(new File(filePath).toPath());
    }

    @Override
    public String getFileUrl(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        return "file://" + Paths.get(baseDir).resolve(filePath).toAbsolutePath();
    }
}
